<template>
  <div class="system-setting-view">
    <div class="page-title">系统设置</div>
    
    <el-card class="setting-card">
      <el-tabs v-model="activeTab" class="setting-tabs">
        <!-- 个人信息设置 -->
        <el-tab-pane label="个人信息" name="personal">
          <el-form ref="personalForm" :model="personalInfo" label-width="120px" class="setting-form">
            <el-form-item label="头像：">
              <div class="avatar-uploader">
                <el-avatar :size="100" class="current-avatar">
                  <img :src="personalInfo.avatar" alt="医生头像">
                </el-avatar>
                <el-upload
                  class="avatar-upload"
                  action="/api/upload/avatar"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  accept="image/jpeg,image/png"
                >
                  <el-button size="small" type="primary">更换头像</el-button>
                </el-upload>
                <div class="avatar-tip">支持JPG、PNG格式，建议尺寸200x200px</div>
              </div>
            </el-form-item>
            
            <el-form-item label="姓名：" required>
              <el-input v-model="personalInfo.name" placeholder="请输入姓名" />
            </el-form-item>
            
            <el-form-item label="工号：" required>
              <el-input v-model="personalInfo.employeeId" placeholder="请输入工号" disabled />
            </el-form-item>
            
            <el-form-item label="所属科室：" required>
              <el-select v-model="personalInfo.department" placeholder="请选择科室">
                <el-option label="内科" value="internal" />
                <el-option label="外科" value="surgery" />
                <el-option label="儿科" value="pediatrics" />
                <el-option label="妇产科" value="obstetrics" />
                <el-option label="皮肤科" value="dermatology" />
                <el-option label="眼科" value="ophthalmology" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="职称：" required>
              <el-select v-model="personalInfo.title" placeholder="请选择职称">
                <el-option label="主任医师" value="chief" />
                <el-option label="副主任医师" value="associate" />
                <el-option label="主治医师" value="attending" />
                <el-option label="住院医师" value="resident" />
                <el-option label="实习医师" value="intern" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="联系电话：" required>
              <el-input v-model="personalInfo.phone" placeholder="请输入联系电话" />
            </el-form-item>
            
            <el-form-item label="电子邮箱：">
              <el-input v-model="personalInfo.email" placeholder="请输入电子邮箱" />
            </el-form-item>
            
            <el-form-item label="个人简介：">
              <el-input 
                v-model="personalInfo.introduction" 
                type="textarea" 
                rows="4"
                placeholder="请输入个人简介"
              />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="savePersonalInfo">保存修改</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 账户安全设置 -->
        <el-tab-pane label="账户安全" name="security">
          <el-form ref="securityForm" label-width="120px" class="setting-form">
            <el-form-item label="登录账号：">
              <el-input v-model="securityInfo.username" disabled />
            </el-form-item>
            
            <el-divider>修改密码</el-divider>
            
            <el-form-item label="原密码：" required>
              <el-input v-model="securityInfo.oldPassword" type="password" placeholder="请输入原密码" />
            </el-form-item>
            
            <el-form-item label="新密码：" required>
              <el-input 
                v-model="securityInfo.newPassword" 
                type="password" 
                placeholder="请输入新密码"
                :show-password="showNewPassword"
              />
              <el-checkbox 
                v-model="showNewPassword" 
                class="show-password-checkbox"
              >
                显示密码
              </el-checkbox>
              <div class="password-tip">密码长度不少于8位，包含字母和数字</div>
            </el-form-item>
            
            <el-form-item label="确认密码：" required>
              <el-input 
                v-model="securityInfo.confirmPassword" 
                type="password" 
                placeholder="请再次输入新密码"
                :show-password="showConfirmPassword"
              />
              <el-checkbox 
                v-model="showConfirmPassword" 
                class="show-password-checkbox"
              >
                显示密码
              </el-checkbox>
            </el-form-item>
            
            <el-divider>绑定手机</el-divider>
            
            <el-form-item label="手机号码：" required>
              <el-input v-model="securityInfo.phone" placeholder="请输入手机号码" />
            </el-form-item>
            
            <el-form-item label="验证码：" required>
              <el-row :gutter="10">
                <el-col :span="14">
                  <el-input v-model="securityInfo.verifyCode" placeholder="请输入验证码" />
                </el-col>
                <el-col :span="10">
                  <el-button 
                    type="text" 
                    class="get-code-btn"
                    :disabled="codeDisabled"
                    @click="getVerifyCode"
                  >
                    {{ codeText }}
                  </el-button>
                </el-col>
              </el-row>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="saveSecurityInfo">保存修改</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 通知设置 -->
        <el-tab-pane label="通知设置" name="notification">
          <el-form ref="notificationForm" :model="notificationSettings" label-width="120px" class="setting-form">
            <el-form-item label="新挂号通知：">
              <el-switch 
                v-model="notificationSettings.newRegistration" 
                active-text="开启" 
                inactive-text="关闭"
              />
            </el-form-item>
            
            <el-form-item label="预约取消通知：">
              <el-switch 
                v-model="notificationSettings.appointmentCancelled" 
                active-text="开启" 
                inactive-text="关闭"
              />
            </el-form-item>
            
            <el-form-item label="患者复诊提醒：">
              <el-switch 
                v-model="notificationSettings.followUpReminder" 
                active-text="开启" 
                inactive-text="关闭"
              />
            </el-form-item>
            
            <el-form-item label="系统公告通知：">
              <el-switch 
                v-model="notificationSettings.systemAnnouncement" 
                active-text="开启" 
                inactive-text="关闭"
                :disabled="true"
              />
            </el-form-item>
            
            <el-divider>通知方式</el-divider>
            
            <el-form-item label="站内消息：">
              <el-switch 
                v-model="notificationSettings.notifyBySystem" 
                active-text="开启" 
                inactive-text="关闭"
                :disabled="true"
              />
            </el-form-item>
            
            <el-form-item label="短信通知：">
              <el-switch 
                v-model="notificationSettings.notifyBySms" 
                active-text="开启" 
                inactive-text="关闭"
              />
            </el-form-item>
            
            <el-form-item label="邮件通知：">
              <el-switch 
                v-model="notificationSettings.notifyByEmail" 
                active-text="开启" 
                inactive-text="关闭"
              />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="saveNotificationSettings">保存设置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 数据管理 -->
        <el-tab-pane label="数据管理" name="data">
          <el-form label-width="120px" class="setting-form">
            <el-form-item label="数据备份：">
              <el-button type="primary" @click="handleBackup">创建备份</el-button>
              <el-button @click="handleDownloadBackup">下载最新备份</el-button>
              <div class="backup-tip">
                上次备份时间：{{ lastBackupTime }}
              </div>
            </el-form-item>
            
            <el-divider>数据清理</el-divider>
            
            <el-form-item label="缓存清理：">
              <el-button 
                type="primary" 
                text-color="#fff" 
                background="#f59e0b" 
                @click="handleClearCache"
              >
                清理缓存
              </el-button>
              <div class="cache-size">
                当前缓存大小：{{ cacheSize }} MB
              </div>
            </el-form-item>
            
            <el-form-item label="操作日志：">
              <el-select v-model="logRetentionDays" placeholder="日志保留时间">
                <el-option label="7天" value="7" />
                <el-option label="30天" value="30" />
                <el-option label="90天" value="90" />
                <el-option label="180天" value="180" />
                <el-option label="365天" value="365" />
              </el-select>
              <el-button 
                type="text" 
                text-color="#ff4d4f"
                @click="handleClearLogs"
              >
                清空日志
              </el-button>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="saveDataSettings">保存设置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

// 状态管理
const activeTab = ref('personal');

// 个人信息
const personalInfo = reactive({
  avatar: 'https://picsum.photos/id/237/100/100',
  name: '张医生',
  employeeId: 'DOC2023001',
  department: 'internal',
  title: 'chief',
  phone: '13800138000',
  email: 'zhang@example.com',
  introduction: '主任医师，从事内科临床工作20年，擅长心血管疾病的诊断与治疗。'
});

// 安全设置
const securityInfo = reactive({
  username: 'zhangdoc',
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
  phone: '13800138000',
  verifyCode: ''
});

// 密码显示控制
const showNewPassword = ref(false);
const showConfirmPassword = ref(false);

// 验证码控制
const codeText = ref('获取验证码');
const codeDisabled = ref(false);
const codeCountdown = ref(0);

// 通知设置
const notificationSettings = reactive({
  newRegistration: true,
  appointmentCancelled: true,
  followUpReminder: true,
  systemAnnouncement: true,
  notifyBySystem: true,
  notifyBySms: true,
  notifyByEmail: false
});

// 数据管理
const lastBackupTime = ref('2023-05-10 09:30:25');
const cacheSize = ref(28.5);
const logRetentionDays = ref('30');

// 初始化
onMounted(() => {
  // 实际应用中，这里会从后端加载用户设置
  console.log('加载系统设置');
});

// 头像上传成功
const handleAvatarSuccess = (response, file) => {
  personalInfo.avatar = URL.createObjectURL(file.raw);
  ElMessage.success('头像上传成功');
};

// 保存个人信息
const savePersonalInfo = () => {
  axios.put('/api/user/profile', personalInfo)
    .then(response => {
      console.log('个人信息保存成功', response.data);
      ElMessage.success('个人信息保存成功');
    })
    .catch(error => {
      console.error('个人信息保存失败', error);
      ElMessage.error('保存失败，请稍后重试');
    });
};

// 获取验证码
const getVerifyCode = () => {
  if (!securityInfo.phone) {
    ElMessage.warning('请输入手机号码');
    return;
  }
  
  // 模拟发送验证码
  axios.post('/api/sms/verify-code', {
    phone: securityInfo.phone
  }).then(response => {
    console.log('验证码发送成功', response.data);
    ElMessage.success('验证码已发送');
    
    // 倒计时
    codeDisabled.value = true;
    codeCountdown.value = 60;
    codeText.value = `${codeCountdown.value}秒后重发`;
    
    const timer = setInterval(() => {
      codeCountdown.value--;
      codeText.value = `${codeCountdown.value}秒后重发`;
      
      if (codeCountdown.value <= 0) {
        clearInterval(timer);
        codeText.value = '获取验证码';
        codeDisabled.value = false;
      }
    }, 1000);
  }).catch(error => {
    console.error('验证码发送失败', error);
    ElMessage.error('验证码发送失败，请稍后重试');
  });
};

// 保存安全设置
const saveSecurityInfo = () => {
  if (securityInfo.newPassword && securityInfo.newPassword !== securityInfo.confirmPassword) {
    ElMessage.warning('两次输入的密码不一致');
    return;
  }
  
  if (securityInfo.newPassword && securityInfo.newPassword.length < 8) {
    ElMessage.warning('密码长度不能少于8位');
    return;
  }
  
  axios.put('/api/user/security', securityInfo)
    .then(response => {
      console.log('安全设置保存成功', response.data);
      ElMessage.success('安全设置保存成功');
      // 清空密码字段
      securityInfo.oldPassword = '';
      securityInfo.newPassword = '';
      securityInfo.confirmPassword = '';
      securityInfo.verifyCode = '';
    })
    .catch(error => {
      console.error('安全设置保存失败', error);
      ElMessage.error('保存失败，请稍后重试');
    });
};

// 保存通知设置
const saveNotificationSettings = () => {
  axios.put('/api/user/notification-settings', notificationSettings)
    .then(response => {
      console.log('通知设置保存成功', response.data);
      ElMessage.success('通知设置保存成功');
    })
    .catch(error => {
      console.error('通知设置保存失败', error);
      ElMessage.error('保存失败，请稍后重试');
    });
};

// 创建备份
const handleBackup = () => {
  axios.post('/api/data/backup')
    .then(response => {
      console.log('数据备份成功', response.data);
      lastBackupTime.value = new Date().toLocaleString();
      ElMessage.success('数据备份成功');
    })
    .catch(error => {
      console.error('数据备份失败', error);
      ElMessage.error('备份失败，请稍后重试');
    });
};

// 下载备份
const handleDownloadBackup = () => {
  window.open('/api/data/backup/download', '_blank');
};

// 清理缓存
const handleClearCache = () => {
  axios.post('/api/data/clear-cache')
    .then(response => {
      console.log('缓存清理成功', response.data);
      cacheSize.value = 0;
      ElMessage.success('缓存清理成功');
    })
    .catch(error => {
      console.error('缓存清理失败', error);
      ElMessage.error('清理失败，请稍后重试');
    });
};

// 清空日志
const handleClearLogs = () => {
  if (confirm('确定要清空所有操作日志吗？此操作不可恢复。')) {
    axios.post('/api/data/clear logs')
      .then(response => {
        console.log('日志清空成功', response.data);
        ElMessage.success('日志清空成功');
      })
      .catch(error => {
        console.error('日志清空失败', error);
        ElMessage.error('操作失败，请稍后重试');
      });
  }
};

// 保存数据设置
const saveDataSettings = () => {
  axios.put('/api/user/data-settings', {
    logRetentionDays: logRetentionDays.value
  }).then(response => {
    console.log('数据设置保存成功', response.data);
    ElMessage.success('数据设置保存成功');
  }).catch(error => {
    console.error('数据设置保存失败', error);
    ElMessage.error('保存失败，请稍后重试');
  });
};
</script>

<style scoped>
.system-setting-view {
  padding: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 500;
  margin-bottom: 20px;
  color: #1e293b;
}

.setting-card {
  padding: 20px;
}

.setting-tabs {
  margin-top: 10px;
}

.setting-form {
  margin-top: 20px;
}

/* 个人信息样式 */
.avatar-uploader {
  display: flex;
  align-items: center;
  gap: 20px;
}

.current-avatar {
  border: 1px solid #e2e8f0;
}

.avatar-upload {
  margin-bottom: 10px;
}

.avatar-tip {
  font-size: 12px;
  color: #64748b;
  margin-top: 5px;
}

/* 安全设置样式 */
.show-password-checkbox {
  margin-top: 10px;
}

.password-tip {
  font-size: 12px;
  color: #64748b;
  margin-top: 5px;
}

.get-code-btn {
  border: 1px solid #3b82f6;
  color: #3b82f6;
  width: 100%;
}

/* 数据管理样式 */
.backup-tip {
  margin-top: 10px;
  font-size: 14px;
  color: #64748b;
}

.cache-size {
  margin-top: 10px;
  font-size: 14px;
  color: #64748b;
}
</style>
    